import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import defaultSettings from '@/utils/get-page-title'

const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  document.title = defaultSettings(to.meta.title)
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      next()
      if (!store.state.user.userInfo.username) {
        await store.dispatch('user/userInfo')
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
